package com.itedge.solutionmanager.service.security;

import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;

import org.springframework.dao.DataAccessException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import com.itedge.solutionmanager.domain.impl.Employee;

/**
 * Custom UserDetailsService implementation using Employee domain object
 * 
 * @author jhe
 *
 */
public class UserDetailsServiceImpl implements UserDetailsService {
	
	@PersistenceContext
    transient EntityManager entityManager;

	/**
	 * Return UserDetails of Employee object
	 */
	@Override
	public UserDetails loadUserByUsername(String usernameParam)
			throws UsernameNotFoundException, DataAccessException {
		
		UserDetails details;
		
		try {
			details = this.entityManager.createQuery("select o from Employee o where o.username = :username", 
					Employee.class).setParameter("username", usernameParam).getSingleResult();
		} catch (DataAccessException e) {
			throw new UsernameNotFoundException(usernameParam);
		} catch (NoResultException e) {
			throw new UsernameNotFoundException(usernameParam);
	    }
		
		return details;
	}

}
